package cl.fbd.widget.model

case class NodeInfo (val id : Int, val parentId: Int, val level: Int, val numChilds: Int, val isCollapsed : Boolean)

/**
 * 
 */

class TreeModel [A, B] (node : A, leafs : List [TreeModel [B, _]], isCollapsed : Boolean)
{
  def this (_node : A) = {
    this (_node, Nil, false)
  }
  
  def this (_node : A, oneLeaf : TreeModel [B, _]) = {
    this (_node, oneLeaf :: Nil, false)
  }
  
  def this (_node : A, leaf : List [TreeModel [B, _]]) = {
    this (_node, leaf, false)
  }
  
  // TO-DO: check if it can be done better (I don't know if it uses tail recursion)
  
  private def appendList (parentId : Int, level : Int, listA : List [Pair [Any, NodeInfo]]) : List [Pair [Any, NodeInfo]] = {
    
    val currentId = listA match {
      case head :: tail => head._2.id + 1
      case Nil => 0
    }
    
    val withNode = (node, NodeInfo (currentId, parentId, level, leafs.size, isCollapsed)) :: listA
    
    leafs match {
      case Nil => withNode
      case listLeaf => {
        var i = withNode; 
        for (leaf <- leafs) i = leaf.appendList (currentId, level + 1, i)
        i
      }
    }
  }
  
  /**
   * currentId, parentId, level, Node content
   */
   
  def preorder () : List [Pair [Any, NodeInfo]] = {
    appendList (0, 0, Nil).reverse
  }
}
